package top.hzy520.security;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

/**
 * @Author: HouZeYu
 * @Description: 验证信息
 * @Date: Created in 15:51 2018/7/8
 */
public class TokenAuthenticationManager implements AuthenticationManager {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        TokenAuthentication tokenAuthentication= (TokenAuthentication) authentication.getPrincipal();
        if (tokenAuthentication.getAuthorities()!=null&&tokenAuthentication.getAuthorities().size()>0){
            GrantedAuthority authority=tokenAuthentication.getAuthorities().iterator().next();
            if ("ROLE_USER".equals(authority.getAuthority())){
                tokenAuthentication.setAuthenticated(true);
                return tokenAuthentication;
            }
            if ("ROLE_VISITOR".equals(authority.getAuthority())){
                tokenAuthentication.setAuthenticated(true);
                return tokenAuthentication;
            }
        }
        throw new BadCredentialException("unknown-error");
    }
}
